from PIL import Image
import ddddocr


def crop_captcha(screenshot_path, location, size):
    """
    从页面截图中裁剪出验证码区域
    参数:
        screenshot_path: 页面截图文件路径
        location: 验证码坐标字典 {'x': x坐标, 'y': y坐标}
        size: 验证码尺寸字典 {'width': 宽度, 'height': 高度}
    返回:
        PIL.Image对象: 裁剪后的验证码图像
    """
    # 裁剪验证码区域
    image = Image.open(screenshot_path)
    crop_box = (location['x'], location['y'],
                location['x'] + size['width'],
                location['y'] + size['height'])
    captcha_img = image.crop(crop_box)
    captcha_img.save("D:/yjweb/temp/captcha.png")  # 保存验证码图片

    # 识别验证码
    ocr = ddddocr.DdddOcr()
    with open("D:/yjweb/temp/captcha.png", 'rb') as f:
        img_bytes = f.read()
    captcha_text = ocr.classification(img_bytes)  # 识别验证码文本

    return captcha_text

if __name__ == '__main__':     # 程序运行入口
    # 调用示例
    screenshot_path = "D:/yjweb/temp/page.png"
    location = {'x': 928, 'y': 290}
    size = {'height': 35, 'width': 100}
    captcha_text = crop_captcha(screenshot_path, location, size)
    print(f"识别出的验证码是: {captcha_text}")
